package com.ruoyi.cmecomon.controller;

import com.ruoyi.cmecomon.domain.SysNoticeCme;
import com.ruoyi.cmecomon.service.ChartService;
import com.ruoyi.cmecomon.service.HomePageService;
import com.ruoyi.cmecomon.vo.bar.BarVo;
import com.ruoyi.cmecomon.vo.bar.Ordertrendvo;
import com.ruoyi.cmelasercladding.domain.ZsCladdingProcess;
import com.ruoyi.cmelasercladding.domain.ZsCladdingUrl;
import com.ruoyi.cmelasercladding.domain.ZxLaserCladdingOrderForm;
import com.ruoyi.cmelasercladding.service.IZsCladdingUrlService;
import com.ruoyi.cmelasercladding.service.IZxLaserCladdingOrderFormService;
import com.ruoyi.cmemetal.domain.ZxOrderForm;
import com.ruoyi.cmemetal.domain.ZxOrderUrl;
import com.ruoyi.cmemetal.domain.ZxPostProcess;
import com.ruoyi.cmemetal.service.IZxOrderFormService;
import com.ruoyi.cmemetal.service.IZxOrderUrlService;
import com.ruoyi.cmenonmetal.domain.ZsOrderUrl;
import com.ruoyi.cmenonmetal.domain.ZsPostProcess;
import com.ruoyi.cmenonmetal.domain.ZxNonmetalOrderForm;
import com.ruoyi.cmenonmetal.service.IZsOrderUrlService;
import com.ruoyi.cmenonmetal.service.IZxNonmetalOrderFormService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.web.controller.common.CommonController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author Zhang Xu
 * @Date 2021/12/16 23:23
 * @Version 1.0
 */
@RestController
public class ComonController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private IZxOrderFormService zxOrderFormService;

    @Autowired
    private IZxNonmetalOrderFormService zxNonmetalOrderFormService;

    @Autowired
    private IZxLaserCladdingOrderFormService zxLaserCladdingOrderFormService;

    @Autowired
    private ChartService chartService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IZxOrderUrlService zxOrderUrlService;

    @Autowired
    private IZsOrderUrlService zsOrderUrlService;
    @Autowired
    private IZsCladdingUrlService zsCladdingUrlService;

    @Autowired
    private HomePageService homePageService;





//    @GetMapping("/comonlist")
//    public Map<String,Object> zxtest(ZxOrderForm zxOrderForm, ZxNonmetalOrderForm zxNonmetalOrderForm, ZxLaserCladdingOrderForm zxLaserCladdingOrderForm){
//        HashMap<String, Object> map = new HashMap<>();
//
//        List<ZxOrderForm> list = zxOrderFormService.selectZxOrderFormList(zxOrderForm);
//        System.out.println("跟据时间查询金属打印" + list.size());
//
//        List<ZxNonmetalOrderForm> zxNonmetalOrderForms = zxNonmetalOrderFormService.selectZxNonmetalOrderFormList(zxNonmetalOrderForm);
//        System.out.println("根据时间查询非金属打印：" + zxNonmetalOrderForms.size());
//
//        List<ZxLaserCladdingOrderForm> zxLaserCladdingOrderForms = zxLaserCladdingOrderFormService.selectZxLaserCladdingOrderFormList(zxLaserCladdingOrderForm);
//        System.out.println("根据时间查询激光熔覆：" + zxLaserCladdingOrderForms.size());
//
//        return map;
//    }

    //根据始末时间获取订单统计的柱状统计图数据
    @GetMapping("/barlist")
    public BarVo zxtest1(ZxOrderForm zxOrderForm, ZxNonmetalOrderForm zxNonmetalOrderForm, ZxLaserCladdingOrderForm zxLaserCladdingOrderForm){
        BarVo barVo = chartService.getBarVo(zxOrderForm,zxNonmetalOrderForm,zxLaserCladdingOrderForm);
        return barVo;
    }

    //根据始末时间获取订单数量交货数量完成率等数据
    @GetMapping("/orderStatisticsBytime")
    public AjaxResult getOrderStatisticsBytime(ZxOrderForm zxOrderForm, ZxNonmetalOrderForm zxNonmetalOrderForm, ZxLaserCladdingOrderForm zxLaserCladdingOrderForm){
    return chartService.getOrderlist(zxOrderForm,zxNonmetalOrderForm,zxLaserCladdingOrderForm);
    }

    //根据始末时间获取交易趋势统计
    @GetMapping("/ordertrend")
    public Ordertrendvo ordertrend(ZxOrderForm zxOrderForm, ZxNonmetalOrderForm zxNonmetalOrderForm, ZxLaserCladdingOrderForm zxLaserCladdingOrderForm, @RequestParam("beginTime")String beginTime, @RequestParam("endTime")String endTime){
        Ordertrendvo ordertrendvo = chartService.getOrdertrendvo(zxOrderForm,zxNonmetalOrderForm,zxLaserCladdingOrderForm,beginTime,endTime);
        return ordertrendvo;
    }


    /**
     * 相关文件上传请求
     * @param whatfile =1 代表上传的是订单管理相关文件，whatfile = -1代表上传的是预处理相关文件
     */
    @PostMapping("/cmecommon/upload")
    @Transactional
    public AjaxResult uploadFile(@RequestParam("file")MultipartFile file, @RequestParam("orderid") Long orderid,@RequestParam("whatfile") Long whatfile) throws Exception
    {

        ZxOrderUrl zxOrderUrl = new ZxOrderUrl();
        System.out.println(orderid);
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);

            zxOrderUrl.setOederid(orderid.toString());
            List<ZxOrderUrl> zxOrderUrls = zxOrderUrlService.selectZxOrderUrlList(zxOrderUrl);
            zxOrderUrl = zxOrderUrls.get(0);

            //更新url
            if(whatfile == 1 ){
                zxOrderUrl.setOrderUpload(url);
                zxOrderUrlService.updateZxOrderUrl(zxOrderUrl);
            }else if(whatfile == -1){
                zxOrderUrl.setPerprocessUpload(url);
                zxOrderUrlService.updateZxOrderUrl(zxOrderUrl);
            }
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @PostMapping("/cmecommon/download/resource")
    public void resourceDownload(@RequestParam("resource")String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {

        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }


//    非金属模块
    /**
     * 相关文件上传请求
     * @param whatfile > 0代表上传的是订单管理相关文件，whatfile < 0代表上传的是预处理相关文件
     */
    @PostMapping("/cmenonmetal/upload")
    @Transactional
    public AjaxResult uploadFile1(@RequestParam("file")MultipartFile file, @RequestParam("orderid") Long orderid,@RequestParam("whatfile") Long whatfile) throws Exception
    {
        ZsOrderUrl zsOrderUrl = new ZsOrderUrl();
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            zsOrderUrl.setOederid(orderid.toString());
            List<ZsOrderUrl> zsOrderUrls = zsOrderUrlService.selectZsOrderUrlList(zsOrderUrl);
            zsOrderUrl = zsOrderUrls.get(0);


            //更新url
            if(whatfile > 0){

                zsOrderUrl.setOrderUpload(url);
                zsOrderUrlService.updateZsOrderUrl(zsOrderUrl);
            }else if(whatfile < 0){
                zsOrderUrl.setPerprocessUpload(url);
                zsOrderUrlService.updateZsOrderUrl(zsOrderUrl);
            }
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @PostMapping("/cmenonmetal/download/resource")
    public void resourceDownload1(@RequestParam("resource" )String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
//激光熔覆模块

    /**
     * 相关文件上传请求
     * @param whatfile > 0代表上传的是订单管理相关文件，whatfile < 0代表上传的是预处理相关文件
     */
    @PostMapping("/cmelasercladding/upload")
    @Transactional
    public AjaxResult uploadFile2(@RequestParam("file")MultipartFile file, @RequestParam("orderid") Long orderid,@RequestParam("whatfile") Long whatfile) throws Exception
    {
        ZsCladdingUrl zsCladdingUrl = new ZsCladdingUrl();
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();

            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            System.out.println("========================================"+url);
            zsCladdingUrl.setOederid(orderid.toString());
            List<ZsCladdingUrl> zsCladdingUrls = zsCladdingUrlService.selectZsCladdingUrlList(zsCladdingUrl);
            zsCladdingUrl = zsCladdingUrls.get(0);




            //更新url
            if(whatfile > 0){

                zsCladdingUrl.setCladdingUpload(url);
                zsCladdingUrlService.updateZsCladdingUrl(zsCladdingUrl);
            }else if(whatfile < 0){
                zsCladdingUrl.setCladdingprocessUpload(url);
                zsCladdingUrlService.updateZsCladdingUrl(zsCladdingUrl);
            }
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 激光熔覆本地资源通用下载
     */
    @PostMapping("/cmelasercladding/download/resource")
    public void resourceDownload2(@RequestParam("resource" )String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception

    {
        System.out.println("111111================"+resource);
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            System.out.println(localPath);
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }



    /**
     * 获取首页通知
     */
    @PreAuthorize("@ss.hasPermi('system:notice:list')")
    @GetMapping("/cmenotic")
    public List<SysNoticeCme> list()
    {
        return homePageService.getCmeSysNotice();
    }

}
